package com.cjx.print.ui;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.cjx.print.App;
import com.cjx.print.R;
import com.cjx.print.interfaces.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * create by cjx on 2024/8/7
 * desc:
 */
public class SingleSelectDialogFragment extends BaseDialogFragment {

    ItemAdapter adapter;
    String title;
    List<ItemEntity> items;
    List<ItemEntity> srcItems;
    Callback<ItemEntity> callback;

    public static SingleSelectDialogFragment newInstance(String title, List<ItemEntity> items, Callback<ItemEntity> callback) {
        SingleSelectDialogFragment fragment = new SingleSelectDialogFragment();
        fragment.title = title;
        fragment.srcItems = items;
        HashMap<String, ArrayList<ItemEntity>> groupMap = new HashMap<>();
        String key = null;
        for (ItemEntity e : items) {
            if (e.group == null) {
                e.group = App.app.getString(R.string.app_default); // 这里还没有SingleSelectDialogFragment的Context
            }
            key = e.group;
//            ArrayList<ItemEntity> itemEntities = groupMap.computeIfAbsent(key, i -> new ArrayList<>(0));
            ArrayList<ItemEntity> itemEntities = groupMap.get(key);
            if(itemEntities == null){
                itemEntities = new ArrayList<>(4);
                groupMap.put(key, itemEntities);
            }
            itemEntities.add(e);
        }
        if (groupMap.size() == 1) {
            fragment.items = groupMap.get(key);
        } else {
            ArrayList<ItemEntity> result = new ArrayList<>();
            for (String k : groupMap.keySet()) {
                result.add(new ItemEntity(k, null, null));
                result.addAll(groupMap.get(k));
            }
            fragment.items = result;
        }
        fragment.callback = callback;
        return fragment;
    }

    @Override
    public int getViewId() {
        return R.layout.dialog_single_select;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (title != null) {
            ((TextView) findViewById(R.id.title)).setText(title);
        }

        RecyclerView recyclerView = findViewById(R.id.right_container);
        GridLayoutManager gridLayoutManager = getGridLayoutManager();
        recyclerView.setLayoutManager(gridLayoutManager);
        adapter = new ItemAdapter(getContext(), items, v -> {
            ItemEntity i = (ItemEntity) v.getTag();
            callback.callback(i);
            dismiss();
        });
        recyclerView.setAdapter(adapter);

        findViewById(R.id.close).setOnClickListener(v -> dismiss());
    }

    private GridLayoutManager getGridLayoutManager() {
        final int SPAN_COUNT = Math.min(items.size(), 3);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), SPAN_COUNT);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                int customItemViewType = adapter.getItemViewType(i);
                if (customItemViewType == adapter.TYPE_ITEM) {
                    return 1;
                } else {
                    return SPAN_COUNT;
                }
            }
        });
        return gridLayoutManager;
    }

    public SingleSelectDialogFragment setTitle(String title) {
        this.title = title;
        return this;
    }

    public SingleSelectDialogFragment setItems(List<ItemEntity> items, Callback<ItemEntity> callback) {
        srcItems = items;
        HashMap<String, ArrayList<ItemEntity>> groupMap = new HashMap<>();
        String key = null;
        for (ItemEntity e : items) {
            if (e.group == null) {
                e.group = App.app.getString(R.string.app_default); // 这里还没有SingleSelectDialogFragment的Context
            }
            key = e.group;
            ArrayList<ItemEntity> itemEntities = groupMap.get(key);
            if(itemEntities == null){
                itemEntities = new ArrayList<>(4);
                groupMap.put(key, itemEntities);
            }
            itemEntities.add(e);
        }
        if (groupMap.size() == 1) {
            this.items = groupMap.get(key);
        } else {
            ArrayList<ItemEntity> result = new ArrayList<>();
            for (String k : groupMap.keySet()) {
                result.add(new ItemEntity(k, null, null));
                result.addAll(groupMap.get(k));
            }
            this.items = result;
        }
        this.callback = callback;
        return this;
    }

    static class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private final int TYPE_GROUP = 0;
        private final int TYPE_ITEM = 1;
        private final List<ItemEntity> list;
        private final int textSize;
        private final int height;
        private final View.OnClickListener listener;

        public ItemAdapter(Context context, List<ItemEntity> list, View.OnClickListener listener) {
            this.list = list;
            this.listener = listener;
            Resources resources = context.getResources();
            this.textSize = resources.getDimensionPixelSize(R.dimen.sp_11);
            this.height = resources.getDimensionPixelSize(R.dimen.dp_36);
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            Context context = viewGroup.getContext();
            if (i == TYPE_ITEM) {
                TextView textView = new TextView(context);
                textView.setBackgroundResource(R.drawable.checkbox_border_primary);
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
                textView.setGravity(Gravity.CENTER);
                textView.setTextColor(ContextCompat.getColor(context, R.color.text_title_dark));
                RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
                int margin = height / 12;
                lp.setMargins(margin, margin, margin, margin);
                textView.setLayoutParams(lp);
                textView.setOnClickListener(listener);
                return new ItemViewHolder(textView);
            } else {
                int padding = height / 6;
                TextView textView = new TextView(context);
                textView.setPadding(padding, padding, padding, padding);
                textView.setTextColor(ContextCompat.getColor(context, R.color.primary));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimensionPixelSize(R.dimen.sp_9));
                return new GroupViewHolder(textView);
            }
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            int type = getItemViewType(i);
            ItemEntity item = list.get(i);
            if (type == TYPE_ITEM) {
                ItemViewHolder ho = (ItemViewHolder) viewHolder;
                ho.textView.setText(item.name);
                ho.textView.setTag(item);
            } else {
                GroupViewHolder ho = (GroupViewHolder) viewHolder;
                ho.textView.setText(item.name);
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        @Override
        public int getItemViewType(int position) {
            ItemEntity itemEntity = list.get(position);
            if (itemEntity.key == null && TextUtils.isEmpty(itemEntity.group)) {
                return TYPE_GROUP;
            }
            return TYPE_ITEM;
        }
    }

    static class GroupViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public GroupViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }

    public static class ItemEntity {
        public String name;
        public String key;
        public int color;
        public String group;

        public ItemEntity(String name, String key, String group) {
            this.name = name;
            this.key = key;
            this.group = group;
            this.color = -99999;
        }

        public ItemEntity(String name, String key, String group, int color) {
            this.name = name;
            this.key = key;
            this.group = group;
            this.color = color;
        }
    }
}
